﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using NBlock.MVCControl;

namespace Cost.Controllers
{
    public class MaterialStorageController : Controller
    {
        #region 构造函数
        private readonly ICostRepository<MaterialPurchase> materialPurchaseRepository;
        private readonly ICostRepository<MaterialPurchaseItem> materialpurchaseitemRepository;
        private readonly ICostRepository<Material> materialRepository;
        private readonly ICostRepository<Storage> storageRepository;
        private readonly ICostRepository<StockRecord> stockrecordRepository;

        public MaterialStorageController(ICostRepository<MaterialPurchase> materialpurchaseRepository,
            ICostRepository<MaterialPurchaseItem> materialpurchaseitemRepository,
            ICostRepository<Material> materialRepository,
            ICostRepository<Storage> storageRepository,
            ICostRepository<StockRecord> stockrecordRepository)
        {
            this.materialPurchaseRepository = materialpurchaseRepository;
            this.materialpurchaseitemRepository = materialpurchaseitemRepository;
            this.materialRepository = materialRepository;
            this.storageRepository = storageRepository;
            this.stockrecordRepository = stockrecordRepository;
        }
        #endregion

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(string Id)
        {
            var data = materialPurchaseRepository.Find(Id);
            if (data == null)
            {
                throw new Exception(string.Format("找不到指定Id（{0}）的采购单，所以无法入库！", Id));
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult EditList(string orderId, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = materialpurchaseitemRepository.GetPageable(pager, d => d.OrderId == orderId, where);
            var list = pageData.Page.ToList();
            foreach (var item in list)
            {
                item.OrderCount = item.OrderCount;
                item.DeliveryCount = item.DeliveryCount ?? item.OrderCount;
                item.StorageCount = item.StorageCount ?? item.OrderCount;
            }
            var data = pager.ToGridData(list, pageData.Total);
            return Json(data);
        }

        [HttpPost]
        public JsonResult Save(string Id, IList<MaterialPurchaseItem> detail)
        {
            var data = materialPurchaseRepository.Find(Id) ?? new MaterialPurchase();
            data.OrderState = "Storage";
            materialPurchaseRepository.Save(data);

            // 先删除所有子表，再保持所有子表数据
            materialpurchaseitemRepository.DeleteAll(m => m.OrderId == data.Id);
            if (detail != null)
            {
                foreach (var m in detail)
                {
                    m.OrderCount = m.OrderCount;
                    m.DeliveryCount = m.DeliveryCount;
                    m.StorageCount = m.StorageCount;
                    m.OrderId = data.Id;
                    m.State = "Storage";
                    materialpurchaseitemRepository.Insert(m);

                    //库存
                    Storage Sordate = storageRepository.Find(s => s.MaterialId == m.MaterialId);
                    if (Sordate == null)
                    {
                        Sordate = new Storage();
                        Sordate.ActualSorage = m.StorageCount;
                        Sordate.MaterialId = m.MaterialId;
                        Sordate.Code = m.Code;
                        Sordate.Name = m.Name;
                        Sordate.Category = m.Category;
                        var Material = materialRepository.Find(m.MaterialId);
                        if (Material != null)
                        {
                            Sordate.Specification = Material.Specification;
                            Sordate.Unit = Material.Unit;
                        }
                        Sordate.Type = "SemiMaterial";
                        Sordate.CurrentPrice = m.Price;
                        storageRepository.Insert(Sordate);
                    }
                    else
                    {
                        Sordate.CurrentPrice = m.Price;
                        Sordate.ActualSorage += m.StorageCount;
                        storageRepository.Save(Sordate);
                    }

                    //保存库存记录
                    StockRecord StockRecorddate = new StockRecord()
                    {
                        Id = Guid.NewGuid().ToString(),
                        MaterialId = m.MaterialId,
                        Type = "采购入库",
                        Count = m.DeliveryCount,
                    };
                    stockrecordRepository.Insert(StockRecorddate);
                }
            }

            return Json(AjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult List(nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = materialPurchaseRepository.GetPageable(pager, m => m.OrderState == "Delivery", where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }
    }
}
